/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.cn360.batch.BuildCn360PropsJob
   Module Description   :

   Date Created      : 2011/7/6
   Original Author   : jeffma
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.cn360.batch;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;

import com.csvreader.CsvWriter;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.thread.batch.AbstractRunJob;
import com.yaodian100.ec.cn360.remote.RemoteCn360ProductService;
import com.yaodian100.ec.product.entity.Brand;
import com.yaodian100.ec.product.service.ProductService;

/**
 * @author jeffma
 * 
 */
public class BuildCn360PropsJob extends AbstractRunJob {

	private ProductService productService;
	private Map<String, Set<String>> props;

	/** default constructor */
	public BuildCn360PropsJob(ProductService productService, List<Map<String, Object>> products) {
		super("BuildCn360PropsJob");
		this.productService = productService;
		this.props = prepareData(products);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.core.thread.batch.AbstractRunJob#execute()
	 */
	@Override
	public void execute() {
		String feedFile = ServerValue.getFrontApachePath() + "3party_ex" + File.separator + "360cn" + File.separator
				+ "yaodian100_f.csv";
		File feedFileObj = new File(feedFile);
		if(feedFileObj.exists()) {
			feedFileObj.delete();
		}
		try {
			CsvWriter writer = new CsvWriter(feedFile, ',', Charset.forName("gb2312"));
			writer.writeRecord(new String[] { "bid", "category_id", "sale_props_type", "props_id", "props_name",
					"props_values" });
			int count = 0;
			String type = "0";
			Map<String, Brand> brandMap = new HashMap<String, Brand>();
			for (String k : props.keySet()) {
				String[] kArray = StringUtils.split(k, "_");
				kArray[1] = StringUtils.remove(kArray[1], "1=");
				kArray[1] = StringUtils.remove(kArray[1], "2=");
				// 销售属性类型，1：颜色、花色。2：大小、尺码。0：非销售属性。
				if (kArray[1].indexOf("颜色") != -1) {
					type = "1";
				} else if (kArray[1].indexOf("尺寸") != -1 || kArray[1].indexOf("尺码") != -1 || kArray[1].indexOf("大小") != -1) {
					type = "2";
				} else {
					type = "0";
				}
				String hash = String.valueOf(k.hashCode() > 0 ? k.hashCode() : -k.hashCode());
				writer.writeRecord(new String[] { RemoteCn360ProductService.BID, kArray[0], type, hash, kArray[1],
						StringUtils.join(props.get(k), ";") });
				count++;
				if (count % 200 == 0) {
					writer.flush();
				}
			}
			writer.flush();
			writer.close();
		} catch (Exception e) {
			logger.error("写档错误", e);
		}
	}

	/**
	 * key "category_id"_"props_name"
	 * 
	 * @param products
	 * @return
	 */
	private Map<String, Set<String>> prepareData(List<Map<String, Object>> products) {
		Map<String, Set<String>> data = new TreeMap();
		for (Map<String, Object> product : products) {
			if (product.get("MAIN_CATEGORY_PATH") == null) {
				logger.warn("product categpry path is null, product id:{}", product.get("PRODUCT_ID"));
				continue;
			}
			if (product.get("MAIN_CODE_LABEL") == null || product.get("MAIN_SPEC_NAME") == null) {
				logger.warn("product main label/name is null, product id:{}", product.get("PRODUCT_ID"));
				continue;
			}
			if (product.get("SECOND_CODE_LABEL") == null || product.get("SECOND_SPEC_NAME") == null) {
				logger.warn("product second label/name is null, product id:{}", product.get("PRODUCT_ID"));
				continue;
			}
			String rootCid = StringUtils.split(product.get("MAIN_CATEGORY_PATH").toString(), "/")[0];
			String propName = product.get("MAIN_CODE_LABEL").toString();
			String key = rootCid + "_" + propName;
			Set propsSet;
			if (data.get(key) == null) {
				propsSet = new HashSet();
				data.put(key, propsSet);
			} else {
				propsSet = data.get(key);
			}
			propsSet.addAll(Arrays.asList(StringUtils.split(product.get("MAIN_SPEC_NAME").toString(), ",")));

			propName = product.get("SECOND_CODE_LABEL").toString();
			key = rootCid + "_" + propName;
			if (data.get(key) == null) {
				propsSet = new HashSet();
				data.put(key, propsSet);
			} else {
				propsSet = data.get(key);
			}
			propsSet.addAll(Arrays.asList(StringUtils.split(product.get("SECOND_SPEC_NAME").toString(), ",")));
		}
		return data;
	}

}
